//
//  SelectTicketNumberView.m
//  LotteryTicket
//
//  Created by BRAINDESIGN on 2019/8/28.
//  Copyright © 2019 hyx. All rights reserved.
//


#import "SelectTicketNumberView.h"

@implementation SelectTicketNumberView

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.frame = frame;
        [self createUI];
    }
    return self;
}
- (void)createUI{
    NSArray *imageAry = @[@"icon_chip_1",@"icon_chip_10",@"icon_chip_100",@"icon_chip_500",@"icon_chip_1000",@"icon_chip_10000",@"icon_chip_50000"];//图片的名字，一定要按 @“icon_chip_ 数值” 这个格式，方便下面获取选择的数值
    CGFloat scrWidth = 50;//选项的宽高
    CGFloat scrMargin = 8;//选项之间的间隔
    self.backgroundColor = [UIColor whiteColor];
    backView = [[UIView alloc] init];
    backView.backgroundColor = UIColorHex(D6DEE9);
    [self addSubview:backView];
    [backView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.mas_bottom).offset(0);
        make.left.equalTo(self.mas_left).offset(0);
        make.right.equalTo(self.mas_right).offset(0);
        make.height.offset(CGRectGetHeight(self.frame) - scrWidth/2 - 10);
    }];
    
    
    self.numberChoiceScrView = [[UIScrollView alloc] init];
    self.numberChoiceScrView.showsHorizontalScrollIndicator = NO;
    self.numberChoiceScrView.contentSize = CGSizeMake(imageAry.count*scrWidth + (imageAry.count-1)*scrMargin, scrWidth);
    [self addSubview:self.numberChoiceScrView];
    [self.numberChoiceScrView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.mas_top).offset(0);
        make.left.equalTo(self.mas_left).offset(15);
        make.right.equalTo(self.mas_right).offset(-100);
        make.height.offset(scrWidth+10);
    }];
    self.numberBtnMutAry = [[NSMutableArray alloc] initWithCapacity:0];
    for (int i = 0; i < imageAry.count; i++) {
        UIButton *btn = [[UIButton alloc] init];
        [btn setImage:[UIImage imageNamed:[imageAry objectAtIndex:i]] forState:UIControlStateNormal];
        btn.imageView.contentMode = UIViewContentModeScaleAspectFit;
        [self.numberChoiceScrView addSubview:btn];
        btn.frame = CGRectMake(i*(scrMargin+scrWidth), 10, scrWidth, scrWidth);
        btn.tag = i;
        [btn addTarget:self action:@selector(clickChooseNumber:) forControlEvents:UIControlEventTouchUpInside];
        NSString *numberStr = [[[imageAry objectAtIndex:i] componentsSeparatedByString:@"icon_chip_"] objectAtIndex:1];//根据字符串@" " 分割字符串并获取数值
        //存储数值（计算数值需要）、btn（后面改变frame需要）
        NSDictionary *dic = @{@"number":numberStr,@"btnView":btn};
        [self.numberBtnMutAry addObject:dic];
    }
    
    self.resetBtn = [[UIButton alloc] init];
//    [self.resetBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    [self.resetBtn setTitle:@"重置" forState:UIControlStateNormal];
//    self.resetBtn.titleLabel.font = [UIFont systemFontOfSize:16];
//    self.resetBtn.backgroundColor = [UIColor redColor];
//    self.resetBtn.clipsToBounds = YES;
//    self.resetBtn.layer.cornerRadius = 2.5;
    [self.resetBtn setBackgroundImage:[UIImage imageNamed:@"btn_game_reset"] forState:UIControlStateNormal];
    [self.resetBtn addTarget:self action:@selector(resetNumber) forControlEvents:UIControlEventTouchUpInside];
    [backView addSubview:self.resetBtn];
    [self.resetBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self->backView.mas_top).offset(25);
        make.left.equalTo(self->backView.mas_left).offset(15);
        make.width.offset(50);
        make.height.offset(30);
    }];
    
    self.inputNumberTxtF = [[UITextField alloc] init];
    self.inputNumberTxtF.placeholder = @"下注金额";
    self.inputNumberTxtF.backgroundColor = [UIColor whiteColor];
    self.inputNumberTxtF.clipsToBounds = YES;
    self.inputNumberTxtF.layer.cornerRadius = 2.5;
    self.inputNumberTxtF.keyboardType = UIKeyboardTypeDecimalPad;
    self.inputNumberTxtF.textAlignment = NSTextAlignmentCenter;
    self.inputNumberTxtF.delegate = self;
    self.inputNumberTxtF.textColor = NINE_COLOR;
    self.inputNumberTxtF.font = MFont(15);
    [self.inputNumberTxtF addTarget:self action:@selector(textFieldChange:) forControlEvents:UIControlEventEditingChanged];
    [backView addSubview:self.inputNumberTxtF];
    [self.inputNumberTxtF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self->backView.mas_top).offset(25);
        make.left.equalTo(self.resetBtn.mas_right).offset(10);
        make.width.offset(80);
        make.height.offset(30);
    }];
    
    self.bettingBtn = [[UIButton alloc] init];
//    [self.bettingBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    [self.bettingBtn setTitle:@"投注" forState:UIControlStateNormal];
//    self.bettingBtn.titleLabel.font = [UIFont systemFontOfSize:18];
//    self.bettingBtn.backgroundColor = [UIColor blueColor];
//    self.bettingBtn.clipsToBounds = YES;
//    self.bettingBtn.layer.cornerRadius = 3;
     [self.bettingBtn setBackgroundImage:[UIImage imageNamed:@"btn_game_betting"] forState:UIControlStateNormal];
    [backView addSubview:self.bettingBtn];
    [self.bettingBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self->backView);
        make.right.equalTo(self->backView.mas_right).offset(-15);
        make.width.offset(70);
        make.height.offset(40);
    }];
    
    self.balanceLabel = [[UILabel alloc] init];
    self.balanceLabel.font = RFont(15);
    self.balanceLabel.textColor = UIColorHex(555555);
    self.balanceLabel.text = @"余额：00.00";
    self.balanceLabel.numberOfLines = 0;
    [backView addSubview:self.balanceLabel];
    [self.balanceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self->backView.mas_top).offset(25);
        make.right.equalTo(self.bettingBtn.mas_left).offset(-10);
        make.left.equalTo(self.inputNumberTxtF.mas_right).offset(10);
        make.height.offset(30);
    }];
    bettingNumber = [NSDecimalNumber decimalNumberWithString:@"0"];
    
    //遮罩视图
    self.view_Mask = [[UIView alloc]initWithFrame:self.bounds];
    self.view_Mask.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.4];
    self.view_Mask.hidden =YES;
    [self addSubview:self.view_Mask];
    
    UILabel *lab_worn = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, self.view_Mask.width, 30)];
    lab_worn.text = @"已封盘";
    lab_worn.textAlignment = NSTextAlignmentCenter;
    lab_worn.textColor = WHITE_COLOR;
    lab_worn.font = MFont(20);
    lab_worn.center = self.view_Mask.center;
    [self.view_Mask addSubview:lab_worn];
}
- (void)resetNumber{
    CGRect frame = hasSelectedBtn.frame;
    frame.origin.y = 10;
    hasSelectedBtn.frame = frame;
    bettingNumber = [NSDecimalNumber decimalNumberWithString:@"0"];
    self.inputNumberTxtF.text = @"";
}
- (void)clickChooseNumber:(UIButton *)btn{
    if (hasSelectedBtn) {
        CGRect frame = hasSelectedBtn.frame;
        frame.origin.y = 10;
        hasSelectedBtn.frame = frame;
    }
    NSDictionary *dic = [self.numberBtnMutAry objectAtIndex:btn.tag];
    UIButton *selectedBtn = [dic objectForKey:@"btnView"];
    NSString *selectedNumberStr = [dic objectForKey:@"number"];
    CGRect frame = selectedBtn.frame;
    frame.origin.y = 0;
    selectedBtn.frame = frame;
    hasSelectedBtn = selectedBtn;
    
    bettingNumber = [bettingNumber decimalNumberByAdding:[NSDecimalNumber decimalNumberWithString:selectedNumberStr]];
    self.inputNumberTxtF.text = [NSString stringWithFormat:@"%@",bettingNumber];
    [self.delegate sendBettingNumber:[bettingNumber floatValue]];
}
- (void)textFieldChange:(UITextField *)txtF{
    if([txtF.text isEqualToString:@""]){
        bettingNumber = [NSDecimalNumber decimalNumberWithString:@"0"];
    }else{
        bettingNumber = [NSDecimalNumber decimalNumberWithString:txtF.text];
    }
    [self.delegate sendBettingNumber:[bettingNumber floatValue]];
}
#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    /*
     * 不能输入.0-9以外的字符。
     * 设置输入框输入的内容格式
     * 只能有一个小数点
     * 小数点后最多能输入两位
     * 如果第一位是.则前面加上0.
     * 如果第一位是0则后面必须输入点，否则不能输入。
     */
    BOOL isHaveDian;
    // 判断是否有小数点
    if ([textField.text containsString:@"."]) {
        isHaveDian = YES;
    }else{
        isHaveDian = NO;
    }
    
    if (string.length > 0) {
        
        //当前输入的字符
        unichar single = [string characterAtIndex:0];
        NSLog(@"single = %c",single);
        
        // 不能输入.0-9以外的字符
        if (!((single >= '0' && single <= '9') || single == '.'))
        {
            NSLog(@"您的输入格式不正确");
            return NO;
        }
        
        // 只能有一个小数点
        if (isHaveDian && single == '.') {
            NSLog(@"最多只能输入一个小数点");
            return NO;
        }
        
        // 如果第一位是.则前面加上0.
        if ((textField.text.length == 0) && (single == '.')) {
            textField.text = @"0";
        }
        
        // 如果第一位是0则后面必须输入点，否则不能输入。
        if ([textField.text hasPrefix:@"0"]) {
            if (textField.text.length > 1) {
                NSString *secondStr = [textField.text substringWithRange:NSMakeRange(1, 1)];
                if (![secondStr isEqualToString:@"."]) {
                    NSLog(@"第二个字符需要是小数点");
                    return NO;
                }
            }else{
                if (![string isEqualToString:@"."]) {
                    NSLog(@"第二个字符需要是小数点");
                    return NO;
                }
            }
        }
        
        // 小数点后最多能输入两位
        if (isHaveDian) {
            NSRange ran = [textField.text rangeOfString:@"."];
            // 由于range.location是NSUInteger类型的，所以这里不能通过(range.location - ran.location)>2来判断
            if (range.location > ran.location) {
                if ([textField.text pathExtension].length > 1) {
                    NSLog(@"小数点后最多有两位小数");
                    return NO;
                }
            }
        }
        
    }
    
    return YES;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.inputNumberTxtF resignFirstResponder];
}
@end
